package cn.example.practice.servlet;

import cn.example.practice.model.User;
import cn.example.practice.db.UserDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Optional;

@WebServlet(name = "UserRegisterServlet", urlPatterns = "/userRegisterServlet")
public class UserRegisterServlet extends HttpServlet {

    private static UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        super.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        String upwd = request.getParameter("cpwd");

        // 验证输入
        if (uname == null || uname.isEmpty() || pwd == null || pwd.isEmpty()) {
            response.getWriter().print("{\"success\": false, \"message\": \"用户名和密码不能为空！\"}");
            return;
        }

        if (!pwd.equals(upwd)) {
            response.getWriter().print("{\"success\": false, \"message\": \"密码和确认密码不匹配！\"}");
            return;
        }

        // 检查用户名是否已存在
        Optional<User> existingUser = userDao.getUserByName(uname);
        if (existingUser.isPresent()) {
            response.getWriter().print("{\"success\": false, \"message\": \"该用户名已被注册！\"}");
            return;
        }

        User u = new User();
        u.setUserName(uname);
        u.setPassword(pwd);
        if (userDao.addUser(u)) {
            Optional<User> loginUser = userDao.getUserByName(uname);
            if (loginUser.isPresent()) {
                request.getSession().setAttribute("loginUser", loginUser.get());
                response.getWriter().print("{\"success\": true, \"message\": \"注册成功！\"}");
            }
        }

    }
}
